<template>
  <div class="page-container">
    <el-card class="main-card">
      <div slot="header" class="card-header">
        <span>用户列表</span>
        <div class="header-operations">
          <el-input
            v-model="searchQuery"
            placeholder="请输入用户名/电子邮箱"
            class="search-input"
            clearable
            prefix-icon="el-icon-search"
          >
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
      </div>
      
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="email" label="电子邮箱" width="180"></el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'success' : 'info'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registrationTime" label="注册时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" @click="handleResetPwd(scope.row)">重置密码</el-button>
            <el-button 
              type="text" 
              @click="handleChangeStatus(scope.row)">
              {{ scope.row.status === 'active' ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getUserList, deleteUser, resetPassword, changeStatus } from '@/api/user'

export default {
  name: 'UserList',
  data() {
    return {
      searchQuery: '',
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userList: []
    }
  },
  methods: {
    // 格式化日期显示
    formatDate(dateStr) {
      if (!dateStr) return '无';
      const date = new Date(dateStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    
    handleDelete(row) {
      this.$confirm('确认删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        // eslint-disable-next-line no-unused-vars
        deleteUser(row.userId).then(_ => {
          this.$message.success('删除成功')
          this.fetchData()
        }).catch(err => {
          console.error('删除失败:', err)
          // 错误会由全局拦截器处理
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {})
    },
    
    handleResetPwd(row) {
      this.$confirm('确认重置该用户的密码吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        // eslint-disable-next-line no-unused-vars
        resetPassword(row.userId).then(_ => {
          this.$message.success('密码已重置')
        }).catch(err => {
          console.error('重置密码失败:', err)
          // 错误会由全局拦截器处理
        }).finally(() => {
          this.loading = false
        })
      }).catch(() => {})
    },
    
    handleChangeStatus(row) {
      const newStatus = row.status === 'active' ? 'locked' : 'active'
      const displayStatus = newStatus === 'active' ? '启用' : '停用'
      
      this.$confirm(`确认${displayStatus}该用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        changeStatus({
          userId: row.userId,
          status: newStatus
        }).then(
          // eslint-disable-next-line no-unused-vars
          _ => {
            this.$message.success('状态修改成功')
            row.status = newStatus
          }).catch(err => {
            console.error('修改状态失败:', err)
            // 错误会由全局拦截器处理
          }).finally(() => {
            this.loading = false
          })
      }).catch(() => {})
    },
    
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    
    fetchData() {
      this.loading = true
      
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize
      }
      
      if (this.searchQuery) {
        params.keyword = this.searchQuery
      }
      
      getUserList(params).then(res => {
        // 从响应中获取数据
        this.userList = res.data.records
        this.total = res.data.total
        
        console.log('用户列表数据:', this.userList)
      }).catch(err => {
        console.error('获取用户列表失败:', err)
      }).finally(() => {
        this.loading = false
      })
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 120px);
}

.main-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #304156;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* Element UI 主题覆盖 */
:deep(.el-button--primary) {
  background-color: #ff6b00;
  border-color: #ff6b00;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus) {
  background-color: #ff8533;
  border-color: #ff8533;
}

:deep(.el-button--text) {
  color: #ff6b00;
}

:deep(.el-button--text:hover),
:deep(.el-button--text:focus) {
  color: #ff8533;
}

:deep(.el-tag--success) {
  background-color: rgba(255, 107, 0, 0.1);
  border-color: rgba(255, 107, 0, 0.2);
  color: #ff6b00;
}

:deep(.el-tag--info) {
  background-color: rgba(144, 147, 153, 0.1);
  border-color: rgba(144, 147, 153, 0.2);
  color: #909399;
}

.el-card {
  border-radius: 8px;
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
}

.el-table {
  color: #304156;
}

.el-table th {
  background-color: #f5f7fa;
  color: #304156;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #ff6b00;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #ff6b00;
}
</style> 